﻿
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
namespace WHLRDF
{

    [System.AttributeUsage(AttributeTargets.Class| AttributeTargets.Method)]
    /// <summary>
    /// 重写验证用户是否登录
    /// </summary>
    public class ApiAuthorizeAttribute :Attribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            string a = AppHttpContext.Current.User.Identity.Name;//|| !AppHttpContext.Current.User.Identity.IsAuthenticated
            if (AppHttpContext.Current==null||AppHttpContext.Current.User==null
                )
            {
                WriteResult(context,"用户未登录，无权访问");
            }
            if (!AppHttpContext.Current.User.Identity.IsAuthenticated)
            {
                if (string.IsNullOrWhiteSpace(ApplicationEnvironments.DefaultSession.UserToken))
                {
                    WriteResult(context, "用户未登录，无权访问");
                }
                else
                {
                   var userEntity=  ApplicationEnvironments.DefaultSession.GetUser<dynamic>();
                    if (userEntity == null)
                    {
                        WriteResult(context, "用户未登录，无权访问");
                    }
                    string token= MD5Helper.MD5Encrypt(userEntity.UserId+userEntity.Password+userEntity.Token).ToLower();
                    if(!ApplicationEnvironments.DefaultSession.UserToken.Equals(token))
                    {
                          WriteResult(context, "用户未登录，无权访问");
                    }
                }
            }
        }
        /// <summary>
        /// 输出错误信息
        /// </summary>
        /// <param name="filterContext"></param>
        /// <param name="strError"></param>
        public void WriteResult(AuthorizationFilterContext filterContext, string strError)
        {
            var areaName = "";
            var actionName = filterContext.RouteData.Values["Action"].ToString();
            var controllerName = filterContext.RouteData.Values["controller"].ToString();
            if (filterContext.RouteData.DataTokens["area"] != null)
            {
                areaName = filterContext.RouteData.DataTokens["area"].ToString();
            }
            //new LogErrorService().Save((!string.IsNullOrEmpty(areaName)?areaName+"/"+controllerName:controllerName),actionName,strError,strError);
            if (AppHttpContext.IsPost && AppHttpContext.IsAjax)
            {
                filterContext.HttpContext.Response.StatusCode = 200;
                filterContext.Result = new JsonResult(AjaxResult.Error(strError, -100));
            }
            else
            {
                filterContext.Result = new RedirectResult("~/login");
                //var view = new ViewResult();
                //view.ViewName = "~/Views/Home/Error.cshtml";
                //view.ViewData = new Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary(new BaseController().ViewData);
                //view.ViewData["Message"] = strError;
                //view.ViewData["Exception"] = new Exception(strError);
                //filterContext.Result = view;

            }

        }

    }
}